package com.qinyi.admin.controller;

import com.qinyi.common.ajax.AjaxCode;
import com.qinyi.common.ajax.AjaxResult;
import com.qinyi.common.utils.ServletUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author wangan on 2019/6/4
 * @description
 */
@Controller
public class SysLoginController {

    public static final Logger log = LoggerFactory.getLogger(SysLoginController.class);

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (ServletUtils.isAjaxRequest(request)) {
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print("{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }
        return "login";
    }


    @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(String username, String password, Boolean rememberMe) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            log.info(new AjaxResult(AjaxCode.SUCCESS).toString());
            AjaxResult ajaxResult = new AjaxResult(AjaxCode.SUCCESS);
            return ajaxResult;
        } catch (AuthenticationException e) {
            return new AjaxResult(AjaxCode.SERVER_ERROR);
        }
    }

}
